from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from . import models


class TopicAdmin(admin.ModelAdmin):
    list_display = ('id', 'text', 'date_added', 'owner', 'entry_count', 'operator')
    list_display_links = ['text', 'id']
    fields = ('text',)

    def save_model(self, request, obj, form, change):
        obj.owner = request.user
        return super().save_model(request, obj, form, change)

    def operator(self, obj):
        """在主题列表上，加一个编辑按钮"""
        return format_html('<a href="{}">编辑</a>', reverse('admin:app01_topic_change', args=(obj.id,)))

    def entry_count(self, obj):
        """显示主题下有多少个entry"""
        return obj.entry_set.count()

    operator.short_description = '操作'
    entry_count.short_description = 'entry数量'


class EntryAdmin(admin.ModelAdmin):
    list_display = ('id', 'tag', 'text', 'date_added', 'topic')


admin.site.register(models.Topic, TopicAdmin)
admin.site.register(models.Entry, EntryAdmin)
